<template>
<div class="buyerlefttotcf">
  <div>
    <el-breadcrumb @click="specialInitialProcess" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/initiatingprocess' }" v-if="isShowItem">{{process[processNumber]}}</el-breadcrumb-item>
      <span @click.stop=";" v-if="isShowSpan">{{process[processNumber]}}<i class="el-icon-arrow-right"></i> </span>
      <span @click.stop=";">9买家付尾款给TCF</span>
    </el-breadcrumb>
  </div>

  <div class="head">
    <h2>尾款收汇通知单</h2>

    <div class="btns clearfix">
      <el-button class="bind" v-show="!editable" :disabled="!editable2" type="primary" @click="bindOrder">绑定订单</el-button>

      <!-- <el-button v-if="editable" class="export" :disabled="!editable2"  type="primary">导出</el-button>
      <el-button v-else class="export" :disabled="true"  type="primary">导出</el-button> -->
    </div>

    <div class="select-orders">
      <el-row :gutter="20">
        <el-col :span="10">
          <div>
            <p class="select-orders-line">
              选中的外贸订单
              <el-button v-show="editable"  @click="bindOrder" type="text">点击修改</el-button>
              </p>
            <ul>
              <!-- <li v-if="showftc"><a :href="'#/initiatingprocess/businessform?dTab=3&formInstId='+ showftc.id + '&formServiceName=' +  showftc.formServiceName">{{saveData.buyerlefttotcf_bindFContracts[0]}}</a></li> -->
              <li><a href="#">{{saveData.buyerlefttotcf_bindFContracts[0]}}</a></li>
            </ul>
          </div>
        </el-col>
        <el-col :span="10" :offset="4">
          <div>
            <p class="select-orders-line">选中的内贸订单</p>
            <ul>
              <!-- <li v-for="item in this.saveData.buyerlefttotcf_bindDContracts ">
                <a href="#">{{item}}</a>
              </li> -->

              <li>
                <a href="#">{{saveData.buyerlefttotcf_bindDContracts[0]}}</a>
              </li>
            </ul>
          </div>
        </el-col>
      </el-row>
    </div>


    <div class="upload">
      <p class="upload-hint">票据/附件</p>
      <div>
        <div class="upload-btn">
          <input type="file"  v-show="editable ? editable2 : false "  name="file" multiple @change="selectFiles">
          <el-button v-if="editable"  :disabled="!editable2" type="primary">选择附件</el-button>
          <el-button v-else :disabled="true" type="primary">选择附件</el-button>
        </div>

        <ul class="upload-files">
          <li @mouseover="handleOver(item)" :key="index"  @mouseout="handleOut(item)" v-for="(item,index) in saveData.attachedFiles">
            <span @click="download(item.id, $event)">{{item.name}}</span>
            <span v-if="editable && item.status" class="el-icon-circle-check" style="color:#67c23a;"></span>
            <span v-else-if="editable" class="el-icon-circle-close" @click="changeFiles(index,item)" style="color:red;"></span>
          </li>
        </ul>
      </div>
    </div>
  </div>

  <div class="bind-window">
    <el-dialog title="订单绑定" width="70%" :visible.sync="dialogCtrl.outerVisible">

      <el-form :inline="true">
        <el-form-item label="订单编号">
          <el-input v-model="orderNumber" placeholder="请输入订单编号"></el-input>
        </el-form-item>
        <el-form-item label="外贸合同号">
          <el-input v-model="foreignTradeContractNumber" placeholder="请输入外贸合同号"></el-input>
        </el-form-item>

        <el-form-item label="买家名称">
          <el-input v-model="buyerName" placeholder="请输入买家名称"></el-input>
        </el-form-item>

        <el-form-item>
          <el-date-picker
          v-model="orangeDate"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOrange">
        </el-date-picker>
      </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="queryFtc(-1)">查询</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="table1Data" style="width: 100%" border>
        <el-table-column prop="table1_orderNumber" label="订单编号" sortable width="240" :sort-method="table1Sort">
          <template slot-scope="scope">
            <span>
              <input type="checkbox" :value="scope.row.table1_id" @click="checkBoxRadio('selForder', $event)" v-model="selectOrder">
              <span>{{scope.row.table1_orderNumber}}</span>
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="table1_ftcNumber" label="外贸合同号" sortable>
        </el-table-column>

        <el-table-column prop="table1_createTime" label="订单生成时间" sortable>
        </el-table-column>

        <el-table-column prop="table1_buyerName" label="买家名称" >
        </el-table-column>

        <el-table-column prop="table1_orderProcess" label="订单流程" >
        </el-table-column>

        <el-table-column prop="table1_orderStatus" label="订单状态" >
        </el-table-column>
      </el-table>

      <div class="pageing">
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.currPage"
        :page-sizes="[20, 30, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.totalSize">
      </el-pagination>

      </div>


      <el-dialog width="50%" title="内贸合同绑定" :visible.sync="dialogCtrl.innerVisible" append-to-body>

        <el-table v-loading="loading" :data="table2Data" style="width: 100%" border>
          <el-table-column prop="table2_dtcNumber" label="内贸合同编号" width="200">
            <template slot-scope="scope">
              <span>
                <input type="checkbox"  @click="checkBoxRadio('selDorder', $event)" :value="scope.row.table2_id" v-model="selectOrder2">
                <span>{{scope.row.table2_dtcNumber}}</span>
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="table2_sellerName" label="供方名称">
          </el-table-column>

          <el-table-column prop="table2_contractAmount" label="合同金额">
          </el-table-column>
        </el-table>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" :disabled="canNotSelect2" @click="bindInnerConfirm">确定</el-button>
          <el-button @click="bindInnerCancel">取 消</el-button>
        </div>
      </el-dialog>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="canNotSelect" @click="bindOuterSelect">选择内贸合同</el-button>
        <el-button @click="bindOuterCancel">取 消</el-button>
      </div>

    </el-dialog>
  </div>


  <div class="buyerlefttotcf-fixed">
    <fixed-form v-if="editable" ref="fixedForm" :saveAndSend="saveAndSend" :editable="editable2" :datas="allData" :sendMenus="sendMenus" processName="buyerlefttotcf" />
    <fixed-form v-else ref="fixedForm" :saveAndSend="false" :editable="false" :datas="allData" :sendMenus="sendMenus" processName="buyerlefttotcf" />
  </div>

</div>
</template>

<script>
import fixedForm from '../common/fixedForm';
import {
  uploadFiles,
  getSendMenus,
  getData,
  queryBindContracts,
  queryBindDtcContracts
} from '@/server/initiatingprocess';

import {
  getStore,
  setStore
} from '@/assets/js/common'

import {filedownload , deleteFile} from '@/server/customermanagement/index.js'

export default {
  created() {
    setStore("flow4-save-status", "unsave");
    this.allData = _.cloneDeep(this.saveData);
  },
  beforeRouteEnter(to, from, next) {
    let dom = document.querySelector('.initiatingprocess  .routers-ctrl');
    if (dom) {
      dom.style.zIndex = '-1';
    }
    next((vm) => {
      //说明从其他位置跳到该流程中
      if (to.query.dTab) {
        vm.processNumber = parseInt(to.query.itemStatus);

        vm.editable = true;

        if (to.query.isHive == 1){
          vm.$store.commit('buyerlefttotcf/SET_SAVE');
          getData({
            formInstId: to.query.formInstId,
            formServiceName: to.query.formServiceName,
            isHive: 1
          }).then((response) => {
            let data = response.data.datas[0];


            //对其中的字符串类型的附件名称，进行分割
            data = JSON.parse(JSON.stringify(data).replace(/(attachedFiles)/g, function(){return 'useless01';}).replace(/(attachedFileList)/g, function() {
              return "attachedFiles";
            }).replace(/(relationFormInst)/g, function(){ return 'relationFormInstId'}), function(k, v) {
              if (k === 'attachedFiles') {
                if (_.isArray(v)) {
                  return v.map((e) => {
                    return {
                      name: e.realFileName,
                      status: 1,
                      id: e.id
                    };
                  });
                } else {
                  return [];
                }
              }
              if (k === 'relationFormInstId'){
                if (_.isPlainObject(v)){
                  return [v];
                } else {
                  return [];
                }
              }

              if ((k.indexOf("_bindFContracts") != -1) || (k.indexOf("_bindDContracts") != -1)) {
                if (_.isString(v)){
                  return v.split(',');
                } else {
                  return [];
                }
              }
              return v;
            });


            for (const key in data) {
              vm.$set(vm.saveData, key, data[key]);
            }


            let approvalIndex, approvalFullName, names = [], originApprovals = _.cloneDeep(vm.saveData.originApprovals);

            if (data.role) {

              vm.editable2 = (data.role.DEFAULT == 'W' ? true : false);
              vm.saveAndSend = vm.editable2;

              let copyApprovals = _.cloneDeep(data.approvals);


              for (let i = 0; i < copyApprovals.length ; i++) {
                for (var prop in originApprovals[i]) {
                  if ((prop != 'rw') && (prop != 'approval_div_name') && (prop != 'item')){
                    originApprovals[i][prop] = copyApprovals[i][prop]
                  }
                }
              }
              vm.$set(vm.saveData, "originApprovals", originApprovals);
              vm.$set(vm.saveData, "isSalesMan", false);
            } else {
              vm.$set(vm.saveData, "isSalesMan", true);
            }


            getSendMenus({
              flowId: to.query.flowId,
              currNodeId: to.query.currNodeId
            }).then((response) => {
              vm.sendMenus = response.data.datas[0];
              vm.updateData();
            });

          });
        } else {
          getData({
            formInstId: to.query.formInstId,
            formServiceName: to.query.formServiceName
          }).then((response) => {
            let data = response.data.datas[0];

            /*
            let data =  {
                "buyerlefttotcf_bindFContracts": "ZS201712038888",
                "buyerlefttotcf_bindDContracts": "ZS20171203F",
                "id": 5,
                "attachedFileList": [
                    {
                        "id": 28,
                        "createTime": 1529894469000,
                        "modifyTime": 1529894471000,
                        "fileName": "attached/1529894469765_98.png",
                        "type": 2,
                        "status": 1,
                        "formInstId": 93,
                        "tabName": "buyerlefttotcf",
                        "tabId": 5,
                        "customerId": null,
                        "realFileName": "98.png"
                    }
                ],
                "formInstId": 93,
                "flowId": 6,
                "formId": 6,
                "formServiceName": "buyerlefttotcf",
                "bindingFormInstId": 23,
                "orderCode": "NO.DD2018051800112",
                "approvals": [],
                "role": [
                    {
                        "id": 314,
                        "createTime": 1525752220000,
                        "modifyTime": null,
                        "formId": 6,
                        "flowId": 6,
                        "flowNodeId": 31,
                        "flowNodeName": "业务填报",
                        "itemName": "buyerlefttotcf_bindFContracts",
                        "permission": "W"
                    },
                    {
                        "id": 315,
                        "createTime": 1525752220000,
                        "modifyTime": null,
                        "formId": 6,
                        "flowId": 6,
                        "flowNodeId": 31,
                        "flowNodeName": "业务填报",
                        "itemName": "buyerlefttotcf_bindDContracts",
                        "permission": "W"
                    },
                    {
                        "id": 316,
                        "createTime": 1525752220000,
                        "modifyTime": null,
                        "formId": 6,
                        "flowId": 6,
                        "flowNodeId": 31,
                        "flowNodeName": "业务填报",
                        "itemName": "item_06_01",
                        "permission": "R"
                    },
                    {
                        "id": 317,
                        "createTime": 1525752220000,
                        "modifyTime": null,
                        "formId": 6,
                        "flowId": 6,
                        "flowNodeId": 31,
                        "flowNodeName": "业务填报",
                        "itemName": "item_06_02",
                        "permission": "R"
                    }
                ]
            };
            */


            //对其中的字符串类型的附件名称，进行分割
            data = JSON.parse(JSON.stringify(data).replace(/(attachedFiles)/g, function(){return 'useless01';}).replace(/(attachedFileList)/g, function() {
              return "attachedFiles";
            }).replace(/(relationFormInst)/g, function(){ return 'relationFormInstId'}), function(k, v) {
              if (k === 'attachedFiles') {
                if (_.isArray(v)) {
                  return v.map((e) => {
                    return {
                      name: e.realFileName,
                      status: 1,
                      id: e.id
                    };
                  });
                } else {
                  return [];
                }
              }
              if (k === 'relationFormInstId'){
                if (_.isPlainObject(v)){
                  return [v];
                } else {
                  return [];
                }
              }

              if ((k.indexOf("_bindFContracts") != -1) || (k.indexOf("_bindDContracts") != -1)) {
                if (_.isString(v)){
                  return v.split(',');
                } else {
                  return [];
                }
              }
              return v;
            });

            for (const key in data) {
              vm.$set(vm.saveData, key, data[key]);
            }

            let approvalIndex, approvalFullName, names = [], originApprovals = _.cloneDeep(vm.saveData.originApprovals) ;

            if (data.role) {
              data.role.forEach((e) => {
                if (e.itemName.indexOf("item") === -1) {
                  vm.$set(vm.roles, e.itemName, e.permission );
                } else {
                  let num = Number(e.itemName[e.itemName.length - 1]) - 1;
                  if (e.permission == 'W') {
                    approvalIndex = num;
                  }
                }
              });

              vm.editable2 = vm.roles.buyerlefttotcf_bindFContracts == 'W' ? true : false;
              vm.saveAndSend = true;

              let copyApprovals = _.cloneDeep(data.approvals);


              if (approvalIndex !== undefined) {
                if (approvalIndex >= 0) {
                  for (let i = 0; i <= approvalIndex; i++) {
                    if (copyApprovals[i]){
                      for (var prop in originApprovals[i]) {
                        if ((prop != 'rw') && (prop != 'approval_div_name') && (prop != 'item')){
                          originApprovals[i][prop] = copyApprovals[i][prop]
                        }
                      }
                      originApprovals[i].approval_id = '' + copyApprovals[i].id;
                    }
                  }
                }


                let date = new Date();
                originApprovals[approvalIndex].rw = 'W';
                originApprovals[approvalIndex].approval_time = date.toLocaleDateString() + ' ' + date.toTimeString().slice(0, 9);
                originApprovals[approvalIndex].approval_username = JSON.parse(getStore('userMsg')).userName;;

              } else if (copyApprovals.length > 0){
                for (let i = 0; i < copyApprovals.length; i++) {

                  for (var prop in originApprovals[i]) {
                    if ((prop != 'rw') && (prop != 'approval_div_name') && (prop != 'item')){
                      originApprovals[i][prop] = copyApprovals[i][prop]
                    }
                  }
                  originApprovals[i].approval_id = '' + copyApprovals[i].id;
                }
              }

              vm.$set(vm.saveData, "originApprovals", originApprovals);
              vm.$set(vm.saveData, "isSalesMan", false);
            } else {
              vm.$set(vm.saveData, "isSalesMan", true);
            }


            getSendMenus({
              flowId: to.query.flowId,
              currNodeId: to.query.currNodeId
            }).then((response) => {
              vm.sendMenus = response.data.datas[0];
              vm.updateData();
            });

          });
        }
      } else {
        // vm.$message({
        //   message: '请先绑定订单，否则无法保存和发送',
        //   type: 'warning',
        //   duration: 3000,
        //   showClose: true
        // });
      }
    });
  },
  beforeRouteLeave(to, from, next){
    document.querySelector('.initiatingprocess  .routers-ctrl').style.zIndex = '-1';
    if (getStore("flow6-save-status") === 'unsave'){
      this.$confirm('您填写的内容尚未保存或发送,是否要离开?', '提示', {
        confirmButtonText: '离开',
        cancelButtonText: '留下',
        type: 'warning'
      }).then(() => {
        next();
      }).catch(() => {
        Array.prototype.forEach.call(document.getElementsByTagName('*'), (e) => {
          e.blur();
        });
        next(false);
      });
    } else {
      next();
    }
  },

  mounted() {
    document.querySelector('.initiatingprocess  .routers-ctrl').style.zIndex = '-1';

    let that = this;
    let closeDom = document.querySelectorAll('.bind-window i.el-dialog__close.el-icon-close');
    for (let i = 0; i < closeDom.length; i++) {
      closeDom[i].onclick = function() {
        that.bindInnerCancel();
      };
    }

    getSendMenus({
      'flowId': 6
    }).then((response) => {
      this.sendMenus = response.data.datas[0];
    });

    //判断面包屑二级路由是否可退回
    let isCreatFlow = getStore('isCreatFlow');
    this.isShowItem = !isCreatFlow ? false : true;
    this.isShowSpan = !isCreatFlow ? true : false;
  },
  beforeDestroy(){
    setStore("flow6-save-status", "unsave");
  },
  methods: {

    /**
     * 更新数据到form
     */
    updateData(){
      this.allData = _.cloneDeep(this.saveData);
    },
    specialInitialProcess() {
      let cls = event.target.classList;
      if (cls.contains("el-icon-arrow-right") && cls.contains("el-breadcrumb__separator")) return;

      let dom = document.querySelector('.initiatingprocess .routers-ctrl');
      if (dom) {
        dom.style.zIndex = '0';
      }
    },
    bindOrder() {
      this.$set(this.dialogCtrl, "outerVisible", true);
      this.bindFContracts = [];
      this.canNotSelect = true;
      this.canNotSelect2 = true;
      this.bbindFContracts = [];
      this.bindDContracts = [];


      this.orderNumber = '';
      this.foreignTradeContractNumber = '';
      this.buyerName = '';
      this.queryFtc(1, 30);
    },


    handleSizeChange(size){
      this.$set(this.page, "pageSize", size);

      //需要重新查询
      this.queryFtc(1, this.page.pageSize);
    },
    handleCurrentChange(currPage){
      this.$set(this.page, "currPage", currPage);
      //需要重新查询
      this.queryFtc(this.page.currPage, this.page.pageSize);
    },

    queryFtc(currPage, pageSize) {
      //通过查询来获得外贸合同订单，并修改table1的数据来进行显示

     let startTime, endTime;
      if (currPage ==  -1){
        currPage = 1;
        this.$set(this.page, "currPage", 1);
        pageSize = this.page.pageSize;
      }

      this.table1Data = [];
      this.table2Data = [];
      this.selectOrder = [];
      this.loading = true;

      if (this.orangeDate) {
        startTime = new Date('' + this.orangeDate[0]).getTime();
        endTime = new Date('' + this.orangeDate[1]).getTime();

      queryBindContracts({
        flowId: 1,
        orderCode: this.orderNumber,
        ftcCode: this.foreignTradeContractNumber,
        buyerName: this.buyerName,
        currPage: currPage - 1,
        pageSize: pageSize,
        gt_createTime: startTime,
        lt_createTime: endTime
      }).then((response) => {

        this.loading = false;
        this.$set(this.page, "totalSize", response.data.totalSize);
        this.queryOrderData = response.data.datas;

        let table1Data = [];
        for (let i = 0; i < this.queryOrderData.length; i++) {

          if (!table1Data[i]) {
            table1Data[i] = {};
          }
          table1Data[i].table1_orderNumber = this.queryOrderData[i].orderCode;
          table1Data[i].table1_ftcNumber = this.queryOrderData[i].ftcCode;
          table1Data[i].table1_buyerName = this.queryOrderData[i].buyerName;
          table1Data[i].table1_id = this.queryOrderData[i].id;


          let date = new Date(this.queryOrderData[i].createTime);
          let m = date.getMonth() + 1;
          m = m < 10 ? '0' + m  : m;
          let d = date.getDate();
          d = d < 10 ? '0' + d  : d;

          table1Data[i].table1_createTime = date.getFullYear() + '-' + m + '-' + d;

          switch(this.queryOrderData[i].formInstStatus){
            case 0:
            case 1:
            table1Data[i].table1_orderStatus = '流转中';
            break;
            case 2:
            table1Data[i].table1_orderStatus = '完结';
            break;
          }

          table1Data[i].table1_orderProcess = this.queryOrderData[i].flowName;
        }

        this.table1Data = table1Data;
      });
    } else {
      queryBindContracts({
        flowId: 1,
        orderCode: this.orderNumber,
        ftcCode: this.foreignTradeContractNumber,
        buyerName: this.buyerName,
        currPage: currPage - 1,
        pageSize: pageSize
      }).then((response) => {

        this.loading = false;
        this.$set(this.page, "totalSize", response.data.totalSize);
        this.queryOrderData = response.data.datas;

        let table1Data = [];
        for (let i = 0; i < this.queryOrderData.length; i++) {

          if (!table1Data[i]) {
            table1Data[i] = {};
          }
          table1Data[i].table1_orderNumber = this.queryOrderData[i].orderCode;
          table1Data[i].table1_ftcNumber = this.queryOrderData[i].ftcCode;
          table1Data[i].table1_buyerName = this.queryOrderData[i].buyerName;
          table1Data[i].table1_id = this.queryOrderData[i].id;


          let date = new Date(this.queryOrderData[i].createTime);
          let m = date.getMonth() + 1;
          m = m < 10 ? '0' + m  : m;
          let d = date.getDate();
          d = d < 10 ? '0' + d  : d;

          table1Data[i].table1_createTime = date.getFullYear() + '-' + m + '-' + d;

          switch(this.queryOrderData[i].formInstStatus){
            case 0:
            case 1:
            table1Data[i].table1_orderStatus = '流转中';
            break;
            case 2:
            table1Data[i].table1_orderStatus = '完结';
            break;
          }

          table1Data[i].table1_orderProcess = this.queryOrderData[i].flowName;
        }

        this.table1Data = table1Data;
      });
    }
  },
    table1Sort(a, b) {
      let a1 = a.toString().slice(a.length - 5);
      let b1 = b.toString().slice(b.length - 5);
      return parseInt(b) - parseInt(b);
    },
    checkBoxRadio(type, event) {
      let value = event.target.value;

      if (type === 'selForder') {

        if (value === this.selectOrder[0]) {
          this.canNotSelect = true;
        } else {
          this.canNotSelect = false;
        }

        this.selectOrder = [value];
        this.showftc = this.queryOrderData.find((e) => {
          return e.id == this.selectOrder[0]
        });

        this.bindFContracts.splice(0, 1, this.showftc.ftcCode);

      } else if (type === 'selDorder') {
        if (value === this.selectOrder2[0]) {
          this.canNotSelect2 = true;
        } else {
          this.canNotSelect2 = false;
        }
        this.selectOrder2 = [value];

        let currDtc = this.queryOrderData2.find((e) => {
          return e.id == this.selectOrder2[0]
        });

        this.bindDContracts.splice(0, 1, currDtc.bd_no);
      }
    },
    bindOuterSelect() {
      let that = this;
      this.$set(this.dialogCtrl, 'innerVisible', true);

      let closeDom = document.querySelectorAll('i.el-dialog__close.el-icon-close');
      for (let i = 0; i < closeDom.length; i++) {
        closeDom[i].onclick = function() {
          that.bindInnerCancel();
        };
      }

      /*
      需要根据当前选中的订单值即 checkedFOrder,来修改 table2Data，用于显示该订单下的内贸订单
      */


      // this.showftc = this.queryOrderData.find((e) => {
      //   return e.ftcCode == this.bindFContracts[0]
      // });

      this.$set(this.saveData, 'orderCode', this.showftc.orderCode);
      this.$set(this.saveData, 'buyerName', this.showftc.buyerName);

      //绑定外贸订单的id
      this.$set(this.saveData, 'bindingFormInstId', this.showftc.id);

      queryBindDtcContracts({
        formInstId: this.showftc.id
      }).then((response) => {
        this.queryOrderData2 = response.data.datas;

        let table2Data = [];

        for (let i = 0; i < this.queryOrderData2.length; i++) {

          if (!table2Data[i]) {
            table2Data[i] = {};
          }
          table2Data[i].table2_dtcNumber = this.queryOrderData2[i].bd_no;
          table2Data[i].table2_sellerName = this.queryOrderData2[i].bd_seller;
          table2Data[i].table2_contractAmount = this.queryOrderData2[i].bd_table1_totalAmount;
          table2Data[i].table2_id = this.queryOrderData2[i].id;
        }
        this.table2Data = table2Data;
      });
      this.updateData();
    },
    bindOuterCancel() {
      this.bindInnerCancel();
    },
    bindInnerConfirm() {
      this.$set(this.dialogCtrl, "outerVisible", false);
      this.$set(this.dialogCtrl, "innerVisible", false);

      if (this.bindDContracts.length === 0) {
        this.bindInnerCancel();
        return;
      }

      this.$set(this.saveData, "buyerlefttotcf_bindFContracts", this.bindFContracts);
      this.$set(this.saveData, "buyerlefttotcf_bindDContracts", this.bindDContracts);
      this.editable = true;

      //勾选的内贸
      // this.showdtcs = this.queryOrderData2.filter((e)=>{
      //   return this.saveData.buyerlefttotcf_bindDContracts.indexOf(e.bd_no) != -1;
      // });

      this.showdtcs[0] = this.queryOrderData2.find((e) => {
        return this.saveData.buyerlefttotcf_bindDContracts[0] == e.bd_no;;
      });
      this.table1Data = [];
      this.table2Data = [];
      this.page.pageSize = 30;
      this.$set(this.page, "pageSize", 30);
      this.updateData();
    },
    bindInnerCancel() {
      this.$set(this.dialogCtrl, "outerVisible", false);
      this.$set(this.dialogCtrl, "innerVisible", false);

      this.bindFContracts = [];
      this.bindDContracts = [];
      this.selectOrder = [];
      this.selectOrder2 = [];

      this.table1Data = [];
      this.table2Data = [];
      this.canNotSelect = true;
      this.canNotSelect2 = true;

      this.page.pageSize = 30;
      this.$set(this.page, "pageSize", 30);
    },
    selectFiles(event) {
      //票据附件
      let self = this,  attachedFiles = _.cloneDeep(this.saveData.attachedFiles);

      //直接上传，并且获得后端返回的文件的url,将url保存到 this.data.attachedFiles中
      uploadFiles(event.target.files).then((resArr) => {
        resArr.forEach(function(res, i) {
          attachedFiles.push({
            name: event.target.files[i].name,
            status: 1,
            id: res.data.datas[0].id
          });
          self.$set(self.saveData, "attachedFiles", attachedFiles);
          self.updateData();
        });
      });
    },
    changeFiles(index,item) {
     let  attachedFiles = _.cloneDeep(this.saveData.attachedFiles)
      deleteFile({'id':item.id}).then((res) => {
        if(res.code != 1 ){
          this.$message.error('删除失败，请检查网络后重试');
        } else {
          attachedFiles.splice(index, 1);
          this.$set(this.saveData, "attachedFiles", attachedFiles);
          this.updateData();
        }
      });
    },
    handleOver(item){
      item.status = 0;
      this.$forceUpdate();
    },
    handleOut(item){
      item.status = 1;
      this.$forceUpdate();
    },
    download(id, event){
      window.open('http://47.104.93.41/api/common/download?id='+id);
    },
  },
  data() {
    return {
      saveData: {
        hasSaved: false,
        attachedFiles: [],
        relationFormInstId: [], //关联订单
        buyerlefttotcf_bindFContracts: [], //绑定的外贸合同
        buyerlefttotcf_bindDContracts: [], //绑定的内贸合同

        bindingFormInstId: '', //绑定的外贸订单的id
        orderCode: '',
        buyerName: '',

        isSalesMan: true,
        newApprovalName: '',

        //该流程中的所有审批项
        approvalNames: ["业务领导审批尾款收汇通知单", "财务审批尾款收汇通知单"],

        newApproval: {
          "approval_opinion":"",
          "approval_username":"",
          "approval_time":"",
          "approval_div_name": ""
        },

        prevApprovals: [],

        remainApprovals: [],

        //该流程中的所有审批项
        originApprovals:[{
          "approval_opinion":"",
          "approval_username":"",
          "approval_time":"",
          "approval_div_name":"业务领导审批尾款收汇通知单",
          "rw": 'R',
          item: 'item_06_01',
        }, {
          "approval_opinion":"",
          "approval_username":"",
          "approval_time":"",
          "approval_div_name":"财务审批尾款收汇通知单",
          "rw": 'R',
          item: 'item_06_02',
        }],
      },
      allData: {},
      roles: {},
      sendMenus: [],
      isShowItem: false,
      isShowSpan: false,
      editable: false,
      editable2: true,
      saveAndSend: true,
      process: ['待发事项', '待办事项', '已办事项','发起流程'],
      processNumber: 3,
      dialogCtrl: {
        outerVisible: false,
        innerVisible: false,
      },
      page: {
        currPage: 1,
        pageSize: 30,
        totalSize: 0
      },
      loading: false,
      selectOrder: [],
      selectOrder2: [],
      bindFContracts: [],
      bindDContracts: [],
      dialogVisible: false, //默认点击发送的弹窗不显示
      canNotSelect: true,
      canNotSelect2: true,
      orderNumber: '',
      foreignTradeContractNumber: '',
      buyerName: '',
      checkedFOrder: [],
      checkedDOrder: [],
      queryOrderData: [],
      queryOrderData2: [],
      showftc: null,
      showdtcs: [],
      table1Data: [],
      table2Data: [],
      orangeDate: '',
      pickerOrange:{
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        }
    }
  },
  props: {
    formIdStart: {
      type: String,
      required: true
    }
  },
  components: {
    fixedForm
  }
}
</script>

<style lang="scss">
.buyerlefttotcf {
    padding: 20px;
    font-size: 15px;

    i.el-breadcrumb__separator {
        margin: 0 !important;
    }

    i.el-breadcrumb__separator[class*=icon] {
        margin: 0 !important;
        padding: 0 9px !important;
    }

    a {
        color: #409EFF;
    }

    .head {
        border: 1px solid #999;
        padding: 20px;
        position: relative;

        > h2 {
            text-align: center;
            padding: 0px 20px;
        }

        .btns {
            position: absolute;
            top: 16px;
            .bind {
                float: left;
            }
            .export {
                float: right;
            }
        }

        .upload {
            padding: 0;
            > div {
                border: 1px solid #999;
                padding: 20px 0 40px 20px;
            }

            .upload-btn {
                position: relative;
                > input {
                    opacity: 0;
                    width: 100px;
                    height: 40px;
                    position: absolute;
                    top: 0;
                    left: 0;
                }
            }

            .upload-files {

                > li {
                    width: 300px;
                    padding: 10px 0;
                    transition: all 0.5s linear;

                    &:hover {

                      >span {
                        color: #409EFF;
                      }
                    }
                  }

                font-size: 16px;
                span {
                    padding: 0 10px;
                    cursor: pointer;
                    display: inline;
                }
                span.el-icon-close:hover {
                    cursor: pointer;
                }
            }
            .upload-hint {
                font-size: 20px;
                margin-bottom: 10px;
            }
        }

        .select-orders {
            padding: 30px 0;

            li {
                padding: 5px 0;
            }
            .select-orders-line {
              height: 40px;
              line-height: 40px;
            }
        }

    }

    .bind-window {
        .el-form--inline .el-form-item {
            margin-right: 15px;
        }

        td {
            border: 1px solid #e6ebf5;
        }

        td:not(.el-table_1_column_1) {
            width: 120px;
            min-width: 120px;
        }

        .dialog-footer {
            text-align: center;
            button {
                margin-right: 80px;
            }
        }

        a {
            color: #409EFF;
        }

    }

    .buyerlefttotcf-fixed {
        border: 1px solid #999;
        margin-top: 20px;
    }
}
</style>
